// 监听扩展图标点击事件
chrome.action.onClicked.addListener((tab) => {
    // 创建新标签页并打开 newtab.html
    chrome.tabs.create({
        url: chrome.runtime.getURL('newtab.html')
    });
});

// 监听来自内容脚本或弹出窗口的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'sendHttpRequest') {
        // 处理HTTP请求
        handleHttpRequest(request.data)
            .then(response => {
                sendResponse({ success: true, data: response });
            })
            .catch(error => {
                sendResponse({ success: false, error: error.message });
            });

        // 返回true表示将异步发送响应
        return true;
    }
});

// 处理HTTP请求的函数
async function handleHttpRequest(requestData) {
    const { url, method, headers, body, timeout } = requestData;

    try {
        // 记录开始时间
        const startTime = Date.now();

        // 构建fetch选项
        const fetchOptions = {
            method: method,
            headers: headers,
        };

        // 如果有请求体，添加到选项中
        if (body && ['POST', 'PUT', 'PATCH'].includes(method)) {
            fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
        }

        // 创建AbortController来处理超时
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), timeout || 30000);

        fetchOptions.signal = controller.signal;

        // 发送请求
        const response = await fetch(url, fetchOptions);

        // 清除超时
        clearTimeout(timeoutId);

        // 计算响应时间
        const responseTime = Date.now() - startTime;

        // 获取响应头
        const responseHeaders = {};
        response.headers.forEach((value, key) => {
            responseHeaders[key] = value;
        });

        // 获取响应体
        let responseData;
        const contentType = response.headers.get('content-type');

        if (contentType && contentType.includes('application/json')) {
            try {
                responseData = await response.json();
            } catch (e) {
                responseData = await response.text();
            }
        } else {
            responseData = await response.text();
        }

        // 返回响应数据
        return {
            status: response.status,
            statusText: response.statusText,
            headers: responseHeaders,
            data: responseData,
            responseTime: responseTime,
            url: response.url
        };

    } catch (error) {
        // 处理错误
        if (error.name === 'AbortError') {
            throw new Error('请求超时');
        } else if (error.name === 'TypeError') {
            throw new Error('网络错误或URL无效');
        } else {
            throw new Error(error.message || '请求失败');
        }
    }
}